<template>
  <!-- 合同管理 -->
  <div class="contract_list">
    <div class="btns" style="padding:1em;margin-bottom:1em;background:#fff">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="toAdd">添加</el-button>
      <el-select v-model="searchForm.purProjectId" style="margin-right: 6px" filterable clearable placeholder="请选择项目" value-key="name">
        <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id" />
      </el-select>
      <el-input v-model="searchForm.contractName" type="text" size="small" placeholder="合同名" clearable/>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="toSearch">查询</el-button>
    </div>
    <el-card shadow="never">
      <div slot="header" class="index-md-title">
        <span>采购合同表</span>
      </div>
      <a-table
        class="status-table"
        size="small"
        ref="contracts"
        :rowKey="record => record.id"
        :loading="contractsLoading"
        :pagination = pagination
        :data-source="contracts"
        :customRow="rowClick"
        :scroll="{ x: 1000}"
        :row-class-name="tableRowClassName"
        >
        <a-table-column title="序号" align="center" :width="60">
          <template slot-scope="text, record, index">
            {{index+1}}
          </template>
        </a-table-column>
        <a-table-column align="center" :width="140" key="contractName" title="合同名" data-index="contractName" />
        <a-table-column align="center" :width="160" key="contractNo" title="合同编号" data-index="contractNo" />
        <a-table-column align="center" :width="160" key="contractTotalprice" title="合同总价(￥/元)" data-index="contractTotalprice" />
        <a-table-column align="center" :width="160"  key="time" title="生成时间" data-index="time">
          <template slot-scope="text">
            {{dateTimeFormat(text)}}
          </template>
        </a-table-column>
        <!--<a-table-column :width="100" align="center" v-for="item in audits" :key="item.key" :title="item.title" :data-index="item.key">
          <template slot-scope="text, record, index">
            <el-switch
              v-model.string="text"
              active-color="#42B983"
              inactive-color="#8b8b8b"
              :active-value="1"
              :inactive-value="0"
              @change="switchChange(text, index, item.key)"
            >
            </el-switch>
          </template>
        </a-table-column>-->
        <a-table-column title="审核进度" align="center" :width="260">
          <template slot-scope="text, record">
            <a-tooltip v-if="!(record.firstAudit==null && record.secondAudit==null && record.threeAudit==null)" :destroyTooltipOnHide="true">
              <div slot="title">
                <el-row style="width: 260px;padding-right:6px">
                  <el-col v-if="record[item['key']]!=null" v-for="(item, index) in audits" :key="index" class="progress-tooltip-col" :span="24/countProgress(record.firstAudit, record.secondAudit, record.threeAudit)">
                    <div class="progress-tooltip-col-div" style="border-color: #fff; border-bottom: 1px solid"><a-icon theme="filled" :style="{color: checkIcon[record[item['key']]].color}" :type="checkIcon[record[item['key']]].type" /></div>
                    <div class="progress-tooltip-col-div">{{record[item['remark']]}}</div>
                  </el-col>
                </el-row>
              </div>
            <a-progress
              :stroke-color="{
                from: '#108ee9',
                to: '#87d068',
              }"
              :percent="calculateProgress(record.firstAudit, record.secondAudit, record.threeAudit)"
              status="active"
            />
            </a-tooltip>
            <el-tag v-else type="info">{{'未送审'}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column align="center" :width="120" key="remark" title="备注" data-index="remark" />
        <a-table-column fixed="right" align="center" :width="350" key="action" title="操作">
          <template slot-scope="text, record, index">
            <el-button @click.native.stop="editContract(record)" icon="el-icon-edit" type="success" size="mini" style="padding: 7px 10px;">修改</el-button>
            <el-button @click.native.stop="toCheck(record)" v-if="record.firstAudit==null && record.secondAudit==null && record.threeAudit==null" type="success" icon="el-icon-s-promotion" size="mini" style="padding: 7px 10px;">送审</el-button>
<!--            <el-button @click.native.stop="setProp(record.id)" v-else-if="calculateProgress(record.firstAudit, record.secondAudit, record.threeAudit) == 100" size="mini" type="primary" icon="el-icon-setting" style="padding: 7px 10px;">属性</el-button>-->
            <el-button @click.native.stop="upload(record, index)" :loading="uploadLoading[index]" type="primary" size="mini" style="padding: 7px 10px;" icon="el-icon-upload">附件</el-button>
            <el-button @click.native.stop="deleteContract(record, index)" icon="el-icon-delete" type="danger" size="mini" style="padding: 7px 10px;">删除</el-button>
          </template>
        </a-table-column>
      </a-table>
    </el-card>
    <el-card shadow="never" style="margin-top: 1em">
      <div slot="header" class="index-md-title">
        <span>合同供货明细</span>
        <span v-if="currentContract!='' && currentContract">【{{currentContract}}】</span>
      </div>
      <div>
        <el-button @click="importData" type="primary" icon="el-icon-download" size="mini">导出</el-button>
        <el-button :disabled="selectedRowKeys.length>0?false:true" @click="deleteDetail" type="danger" icon="el-icon-delete" size="mini" >删除</el-button>
        <el-button @click="addDetailData" type="primary" icon="el-icon-plus" size="mini" style="float: right">添加明细</el-button>
      </div>
      <div style="margin-top: 10px">
        <a-table
          size="small"
          :data-source="detail.data"
          :rowKey="record => record.id"
          :loading="detail.loading"
          :pagination="detail.pagination"
          :scroll="detail.data.length > 0 ?{ x: 1300}:{}"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <a-table-column defaultSortOrder="ascend" :sorter="(a, b) => a.sort-b.sort" title="序号" key="sort" data-index="sort" align="center" :width="50" />
          <a-table-column :width="100" ellipsis="true" key="item" title="设备" data-index="item" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.supplier" title="供应商" data-index="purchaseSupply.supplier" align="center" />
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.brand" title="品牌" data-index="purchaseSupply.brand" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.model" title="规格型号" data-index="purchaseSupply.model" align="center"/>
          <a-table-column :width="70" key="purchaseSupply.price" title="单价" data-index="purchaseSupply.price" align="center"/>
          <a-table-column :width="80" title="总价" align="center">
            <template slot-scope="text, record">
              {{Number(record.purchaseSupply.price*record.number).toFixed(2)}}
            </template>
          </a-table-column>
          <a-table-column :width="50" key="unit" title="单位" data-index="unit" align="center"/>
          <a-table-column :width="70" key="number" title="数量" data-index="number" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="params" title="技术要求" data-index="params" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.params" title="实际参数" data-index="purchaseSupply.params" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.warranty" title="货期" data-index="purchaseSupply.warranty" align="center"/>
          <a-table-column :width="100" ellipsis="true" key="purchaseSupply.remark" title="商家备注" data-index="purchaseSupply.remark" align="center"/>
          <!--<a-table-column :width="120" fixed="right" key="action" title="操作" align="center">
            <template slot-scope="text, record">
              <el-button @click="editPrice('供货价', record.purchaseSupply)" type="success" icon="el-icon-edit" size="mini" style="padding: 7px 10px;">供货价</el-button>
            </template>
          </a-table-column>-->
        </a-table>
      </div>
    </el-card>

    <!-- 模态框 -->
    <el-dialog v-el-drag-dialog title="修改" :visible.sync="dialogVisible">
      <el-form ref="form" status-icon :model="form" :rules="rules">
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="合同名" label-width="80px" prop="contractName">
              <el-input v-model="form.contractName" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="合同编号" label-width="80px" prop="contractNo">
              <el-input v-model="form.contractNo" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" label-width="80px" prop="remark">
          <el-input type="textarea" v-model="form.remark" autocomplete="off" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="付款方式" label-width="80px" size="small" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="应付款" size="small">
                <el-option v-for="item in ['预付款', '货到付款', '款到发货']" :key="item" :value="item" :label="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="应付款(元)" label-width="80px" size="small" prop="payable">
              <el-input v-model="form.payable" clearable placeholder="应付款金额" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="付款时间" label-width="80px" size="small" prop="payableTime">
              <el-date-picker v-model="form.payableTime" value-format="timestamp" clearable placeholder="预计付款时间" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="付款备注" label-width="80px" size="small" prop="payableTime">
              <el-input v-model="form.payableRemark" clearable placeholder="付款备注" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="保证金(元)" label-width="80px" size="small" prop="bond">
              <el-input v-model="form.bond" clearable placeholder="金额" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="应缴纳时间" label-width="80px" size="small" prop="bondTime">
              <el-date-picker v-model="form.bondTime" value-format="timestamp" clearable placeholder="应缴纳时间(保证金)" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="应缴纳备注" label-width="80px" size="small" prop="bondTime">
              <el-input v-model="form.bondRemark" clearable placeholder="应缴纳备注" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :lg="8" :sm="24">
            <el-form-item label="质保金(元)" label-width="80px" size="small" prop="retentionMoney">
              <el-input v-model="form.retentionMoney" clearable placeholder="金额" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="应缴纳时间" label-width="80px" size="small" prop="retentionTime">
              <el-date-picker v-model="form.retentionTime" value-format="timestamp" clearable placeholder="应缴纳时间(质保金)" size="small" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :sm="24">
            <el-form-item label="应缴纳备注" label-width="80px" size="small" prop="bondTime">
              <el-input v-model="form.retentionRemark" clearable placeholder="应缴纳备注" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="saveRecordHandler('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="送审" :visible.sync="checkDialogVisible">
      <el-form :model="toCheckDialogForm" >
        <el-form-item label="合同名" label-width="80px" prop="contractName">{{toCheckDialogForm.contractName}}</el-form-item>
        <el-form-item label="合同编号" label-width="80px" prop="contractNo">{{toCheckDialogForm.contractNo}}</el-form-item>
        <el-form-item label="审核流程" label-width="80px" prop="checkProcess">
          <el-slider
            v-model="toCheckDialogForm.checkProcess"
            :marks="marks"
            :show-tooltip="false"
            :step="30"
            show-stops
            style="padding: 0 1em">
          </el-slider>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="checkDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="sendCheckHandler">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="上传附件" :visible.sync="uploadDialogVisible">
      <el-form :model="uploadForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同名" label-width="80px" prop="contractName">{{uploadForm.contractName}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" label-width="80px" prop="contractNo">{{uploadForm.contractNo}}</el-form-item>
          </el-col>
        </el-row>
        <div>
          <a-upload-dragger
            name="file"
            :multiple="true"
            :action="fileUploadUrl"
            withCredentials
            list-type="picture"
            :before-upload="beforeUpload"
            :file-list="fileList"
            @change="uploadStatusChange"
            :headers="headers"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text" style="color: #40a9ff">
              上传合同文件
            </p>
            <p class="ant-upload-text">
              点击或者拖拽文件来上传
            </p>
            <p class="ant-upload-hint">
              支持单个或多个文件上传. 单个文件请不要超过12M
            </p>
          </a-upload-dragger>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="uploadSubmitLoading" size="small" @click="uploadHandler">提 交</el-button>
      </div>
    </el-dialog>

    <!--新增明细模态框-->
    <el-dialog v-el-drag-dialog :visible.sync="dialog.visible" title="选择添加项" style="width: 120%">
      <el-form v-model="dialog.form" status-icon>
        <a-row style="margin: 0 0 1em 0">
          <a-col :span="10">
            <el-select v-model="dialog.form.proIds" multiple filterable clearable placeholder="请选择项目" value-key="name">
              <el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id" />
            </el-select>
          </a-col>
          <a-col :span="4">
            <el-input v-model="dialog.form.name" type="text" placeholder="设备名"></el-input>
          </a-col>
          <a-col :span="4">
            <el-input v-model="dialog.form.supplier" type="text" placeholder="供应商"></el-input>
          </a-col>
          <a-col :span="6">
            <el-button style="margin-left: 5em" type="primary" icon="el-icon-search" @click="toSearchItems">查询</el-button>
          </a-col>
        </a-row>
        <a-card style="padding: 0px 0px;">
          <a-table
            :loading = "dialog.loading"
            :data-source = "dialog.data"
            size = "small"
            :rowKey="record => record.id"
            :pagination="dialog.pagination"
            :scroll="dialog.data.length>0?{x:1300}:{}"
            :row-selection="{ selectedRowKeys: dialog.selectedRowKeys, onChange: dialogSelectionChange, selections: [{
                key: 'all-data',
                text: '全选',
                onSelect: () => {
                  this.dialog.selectedRowKeys =  dialog.data.map(item=>{return item.id});
                },
            }]}">
            <a-table-column :width="60" key="sort" title="序号" data-index="sort" ellipsis="true" align="center"/>
            <a-table-column :width="80" align="center" title="状态" key="contractId" data-index="contractId">
              <template slot-scope="text">
                <el-tag :type="text? 'success':'info'">{{ text?'有合同':'无合同' }}</el-tag>
              </template>
            </a-table-column>
            <a-table-column :width="100" key="item" title="设备名" data-index="item" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="number" title="数量" data-index="number" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="purchaseSupply.supplier" title="供货商" data-index="purchaseSupply.supplier" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="purchaseSupply.model" title="供货型号" data-index="purchaseSupply.model" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="purchaseSupply.brand" title="供货品牌" data-index="purchaseSupply.brand" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="purchaseSupply.params" title="供货参数" data-index="purchaseSupply.params" ellipsis="true" align="center"/>
            <a-table-column :width="100" key="purchaseSupply.price" title="供货价" data-index="purchaseSupply.price" ellipsis="true" align="center"/>
            <a-table-column :width="100" title="供货总价" align="center">
              <template slot-scope="text, record">
                {{Number(record.purchaseSupply.price*record.number).toFixed(2)}}
              </template>
            </a-table-column>
          </a-table>
        </a-card>
      </el-form>
      <div slot="footer" class="dialog-footer" style="background-color: #f5f5f5">
        <div style="text-align: center">
          <el-button size="small" @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" :loading="dialog.submitLoading" size="small" @click="batchSelected">选取</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import request from '@/utils/request'
  import '@/styles/auto-style.css'
  import { getUser } from '@/utils/auth'
  import { dateTimeFormat } from '@/utils/format'
  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import { beforeUpload, uploadStatusChange } from '@/utils/upload'
  import elDragDialog from '@/directive/el-drag-dialog'
  import { getToken } from '@/utils/auth'

  const fileUploadUrl = process.env.VUE_APP_BASE_API + 'file/uploadCache'

  export default {
    directives: { elDragDialog },
    data() {

      var validNo = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }
        request.get('/purchase/purchaseContractGenerate/findContractNo',{
          params: { contractNo: value }
        })
        .then(response => {
          if (response.data > 0 && value!=this.contractNo) {
            callback(new Error('合同编号已存在'))
          }else {
            callback()
          }
        })
      };
      return {
        headers: {"X-Token": getToken()},
        selectedRowKeys: [],
        pagination: {
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          current: 1,
          pageSize: 10,
          total: 0,
          onChange: (item) => {
            this.pagination.current = item
            this.toSearch()
          },
          onShowSizeChange: (current, pageSize) => {
            this.pagination.pageSize = pageSize
            this.toSearch()
          }, // 改变每页数量时更新显示
        },
        detail: {
          loading: false,
          data: [],
          selectedRowKeys: [],
          pagination: {
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.detail.pagination.current = item
              this.toSearchDetail(this.selectKey)
            },
            onShowSizeChange: (current, pageSize) => {
              this.detail.pagination.pageSize = pageSize
              this.toSearchDetail(this.selectKey)
            }, // 改变每页数量时更新显示
          }
        },
        dialog: {
          visible: false,
          loading: false,
          form: {},
          submitLoading: false,
          data: [],
          selectedRowKeys: [],
          pagination: {
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            current: 1,
            pageSize: 10,
            total: 0,
            onChange: (item) => {
              this.dialog.pagination.current = item
              this.toSearchItems()
            },
            onShowSizeChange: (current, pageSize) => {
              this.dialog.pagination.pageSize = pageSize
              this.toSearchItems()
            }, // 改变每页数量时更新显示
          }
        },
        fileUploadUrl,

        contractNo: null,

        uploadForm: {},
        fileList: [],
        uploadKey: true,
        uploadDialogVisible: false,
        uploadSubmitLoading: false,

        uploadLoading: [],

        marks: {
          0: '无审核',
          30: '一级',
          60: '二级',
          90: '三级'
        },
        searchForm: {},
        contracts: [],
        contractsLoading: false,
        projects: [],

        checkIcon: [
          { color: '#909399', type: 'question-circle' },
          { color: '#13ce66', type: 'check-circle' },
          { color: '#ff4949', type: 'close-circle'},
        ],

        audits: [
          { key: 'firstAudit', title: '一级审核', remark: 'firstRemark' },
          { key: 'secondAudit', title: '二级审核', remark: 'secondRemark' },
          { key: 'threeAudit', title: '三级审核', remark: 'threeRemark'}
        ],

        title: '',
        dialogVisible: false,
        form: {},

        rules: {
          contractNo: [
            { validator: validNo, trigger: 'blur'}
          ],
          contractName: [
            { required: true, message: '不能为空', trigger: 'blur'}
          ],
        /*  projectId: [
            { required: true, message: '不能为空', trigger: 'blur'}
          ],*/
          // paymentMethod: [
          //   { required: true, message: '不能为空', trigger: 'blur'}
          // ],
          // payable: [
          //   { required: true, pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
          // ],
          // bond: [
          //   { required: true, pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
          // ],
        },

        toCheckDialogForm: {},
        checkDialogVisible: false,

        selectKey: '',
        currentContract: '',
        currentContractId: null,

        windowWidth: document.documentElement.clientWidth, // 屏幕实时宽度
        url: {
          findItemsAndSupplyByProjectId: '/purchase/generatePurchaseContract/findItemsAndSupplyByProjectId',
          findSupplyByContractId: '/purchase/contractManagement/findSupplyByContractId',
          batchSelectedItems: '/purchase/contractManagement/batchSelectedItems',
          batchDeletedItems: '/purchase/contractManagement/batchDeletedItems',
          importContract: '/purchase/contract/importContract'
        }
      }
    },
    created() {
      this.loadProjects()
    },
    mounted() {
      var that = this;
      // <!--把window.onresize事件挂在到mounted函数上-->
      window.onresize = () => {
        return (() => {
          window.fullWidth = document.documentElement.clientWidth;
          that.windowWidth = window.fullWidth; // 宽
        })()
      };
    },
    methods: {
      importData(){
        if(this.currentContractId){
          getAction(this.url.importContract, {id: this.currentContractId})
          .then(resp =>{
            let list = []
            let supplier = null
            import('@/vendor/Export2Excel').then(excel => {
              const tHeader = ['序号', '设备名称', '供应商', '型号', '配置要求', '商家参数', '单位', '数量', '单价', '总价', '品牌', '货期', '质保期', '备注']
              const filterVal = ['sort', 'name', 'supplier', 'suModel', 'params', 'suParams', 'unit', 'number', 'price',
                'totalPrice', 'brand', 'delivery', 'warranty', 'remark']

              resp.data.map(i =>{
                supplier = i.supplier
                list.push({
                  sort: i.sort,
                  name: i.name,
                  suModel: i.suModel,
                  params: i.params,
                  suParams: i.suParams,
                  unit: i.unit,
                  number: i.number,
                  price: i.price,
                  brand: i.brand,
                  delivery: i.delivery,
                  warranty: i.warranty,
                  remark: i.remark,
                  supplier: i.supplier,
                  totalPrice: Number(i.price * i.number).toFixed(2)
                })
              })
              console.info(list)
              const data = this.formatJson(filterVal, list)
              console.info(data)
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: supplier
              })
            })
          })
        }
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      deleteDetail() {
        let items = {}
        items["purchaseId"] = this.selectKey
        items["items"] = this.selectedRowKeys
        postActionByJson(this.url.batchDeletedItems, items)
        .then(resp => {
          this.$message({ type:'success', message: resp.message })
        }).catch(()=>{
          this.$message( {type : 'warning', message : '删除失败'} )
        }).finally(()=>{
          this.toSearchDetail(this.selectKey)
          this.toSearchItems()
        })
      },
      rowClick(row, index) {
        return {
          on: {
            click: () => {
              this.currentContract = row.contractName
              this.selectKey = row.id
              this.currentContractId = row.id
              this.toSearchDetail(row.id)
            }
          }
        }
      },
      toSearchDetail(contractId){
        this.detail.loading = true
        postActionByQueryString(this.url.findSupplyByContractId, {
          contractId: contractId,
          pageNum: this.detail.pagination.current,
          pageSize: this.detail.pagination.pageSize
        })
        .then( resp => {
          this.detail.data = resp.data.records
          this.detail.pagination.current = resp.data.current
          this.detail.pagination.pageSize = resp.data.size
          this.detail.pagination.total = resp.data.total
        }).catch(()=>{
          this.$message( {type: 'warning', message: '查询错误'} )
        }).finally(()=>{
          this.detail.loading = false
          this.selectedRowKeys = []
          this.detail.selectedRowKeys = []
          this.dialog.selectedRowKeys = []
        })
      },
      toSearchItems(){
        this.dialog.loading = true
        this.dialog.form.type = 'purchase'
        this.dialog.form.pageNum = this.dialog.pagination.current
        this.dialog.form.pageSize = this.dialog.pagination.pageSize
        postActionByQueryString(this.url.findItemsAndSupplyByProjectId, this.dialog.form)
        .then(resp => {
          if (resp.data){
            this.dialog.data = resp.data.records
            this.dialog.pagination.current = resp.data.current
            this.dialog.pagination.pageSize = resp.data.size
            this.dialog.pagination.total = resp.data.total
          }
        }).catch(()=>{
          this.$message({ type:'warning', message: "查询有误" })
        }).finally(()=>{
          this.dialog.loading = false
          this.selectedRowKeys = []
          this.detail.selectedRowKeys = []
          this.dialog.selectedRowKeys = []
          this.selectedRowKeys = []
          this.detail.selectedRowKeys = []
          this.dialog.selectedRowKeys = []
        })
      },
      addDetailData(){
        if (this.selectKey){
          this.dialog.visible = true
        }else {
          this.$message({ type:'warning', message: "请先点击要添加明细的合同" })
        }
      },
      batchSelected(){
        if (this.dialog.selectedRowKeys.length > 0){
          let items = {}
          items["purchaseId"] = this.selectKey
          items["items"] = this.dialog.selectedRowKeys
          postActionByJson(this.url.batchSelectedItems, items)
          .then(resp => {
            this.$message({ type:'success', message: resp.message })
          }).catch(()=>{
            this.$message( {type : 'warning', message : '选取失败'} )
          }).finally(()=>{
            this.dialog.submitLoading = false
            this.dialog.visible = false
            this.toSearchDetail(this.selectKey)
            this.toSearchItems()
          })
        }else {
          this.$message({ type:'warning', message: "请选择所需添加项" })
        }
      },
      dialogSelectionChange(record){
        const selectedId = []
        record.map(item => {
          selectedId.push(item)
        })
        this.dialog.selectedRowKeys = selectedId
      },
      editContract(record) {
        this.form = record
        this.title = '修改'
        this.contractNo = record.contractNo
        console.log(record)
        this.dialogVisible = true
      },
      deleteContract(row, index){
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        postActionByQueryString('/purchase/contract/deleteById',row)
          .then(resp => {
            this.$message({ message: resp.message, type: 'success' })
            this.toSearch()
            this.rowClick(row)
          })
        })
      },
      uploadHandler() {
        if (this.uploadKey) {
          this.uploadSubmitLoading = true
          const fileList = this.fileList.map(item => {
            console.log(item)
            return { id: item.id, name: item.name, url: item.url, type: 5, operator: item.response.operator }
          })
          console.log(fileList)
          let form = {}
          form.purchaseContract = this.uploadForm
          form.purchaseContract.operator = getUser()
          form.fileList = fileList
          postActionByJson('/purchase/contractManagement/uploadContractFile', form)
            .then(resp=> {
              this.$message({ message: resp.message, type: 'success' })
            })
            .finally(() => {
              this.uploadSubmitLoading = false
              this.uploadDialogVisible = false
            })
        }else {
          this.$message({ message: '文件上传未完成', type: 'warning' })
        }
      },
      beforeUpload,
      uploadStatusChange,
      upload(row, index) {
        this.fileList = []
        this.uploadLoading[index] = true
        getAction('/file/findByOtherId',{otherId: row.id, type: 5})
        .then(resp => {
          resp.data.map(item => {
            let response = item
            response.error = 0
            response.fileId = response.id
            response.fileName = response.name
            this.fileList.push({
              uid: 0-item.id,
              name: item.name,
              operator: item.operator,
              status: 'done',
              response: response,
              url: response.url
            })
          })
          this.uploadDialogVisible = true
          this.uploadForm = row
        })
        .finally(()=>{
          this.uploadLoading[index] = false
        })
      },
      tableRowClassName(row, index){
        if(this.selectKey == row.id) {
          return 'selected'
        }else {
          return ''
        }
      },
      sendCheckHandler() {
        if (this.toCheckDialogForm.id) {
          let form = {}
          form.id = this.toCheckDialogForm.id
          form.sender = getUser()
          switch (this.toCheckDialogForm.checkProcess) {
            case 0: break
            case 30: form.firstAudit = 0;break
            case 60: form.firstAudit = 0;form.secondAudit = 0;break
            case 90: form.firstAudit = 0;form.secondAudit = 0;form.threeAudit = 0;break
          }
          postActionByQueryString('/purchase/contract/purchaseContractSend', form)
          .then( resp => {
            this.$message({ message: resp.message, type: 'success' })
            this.checkDialogVisible = false
            this.toSearch()
          })
        }
      },
      toCheck(record) {
        this.checkDialogVisible = true
        this.toCheckDialogForm = record
      },
      saveRecordHandler(form) {
        let params = this.form
        params.operator = getUser()
        params.projectId = this.searchForm.purProjectId
        this.$refs[form].validate((valid) => {
          if (valid) {
            postActionByQueryString('/purchase/contract/saveOrUpdate', params)
            .then( resp => {
              this.$message({ message: resp.message, type: 'success' })
            }).catch(()=>{
              this.$message.error('提交失败')
            }).finally(()=>{
              this.dialogVisible = false
              this.toSearch()
            })

          }else {
            console.log('error commit')
            return false
          }
        })
      },
      countProgress(a, b, c) {
        let m = 0
        if (a!=null) {
          m ++
        }
        if (b!=null) {
          m ++
        }
        if (c!=null) {
          m ++
        }
        return m
      },
      calculateProgress(a, b, c) {
        let m = this.countProgress(a, b, c)
        let n = 0

        if (a == 1) {
          n ++
        }
        if (b == 1) {
          n ++
        }
        if (c == 1) {
          n ++
        }
        if (m != 0) {
          return parseFloat(parseFloat(n / m * 100).toFixed(2))
        }else {
          return 0
        }
      },
      toAdd() {
        this.contractNo = null
        this.dialogVisible = true
        this.form = {}
        this.title = '新增采购合同'
      },
      toSearch() {
        this.contractsLoading = true
        this.searchForm.projectId = this.searchForm.purProjectId
        this.searchForm.pageNum = this.pagination.current,
        this.searchForm.pageSize = this.pagination.pageSize
        postActionByQueryString('/purchase/contract/findByProjectId', this.searchForm)
        .then(resp => {
          this.contracts = resp.data.records
          this.pagination.current = parseInt(resp.data.current)
          this.pagination.pageSize = parseInt(resp.data.size)
          this.pagination.total = parseInt(resp.data.total)
        })
        .catch(() => {
          this.$message({ type:'warning', message: "查询失败" })
        }).finally(()=>{
          this.contractsLoading = false
        })
      },
      dateTimeFormat,
      onSelectChange(selectedRowKeys, selectedRows) {
        let rows = []
        selectedRows.map(item => {
          if (item.id) {
            rows.push(item.id)
          }
        })
        this.selectedRowKeys = rows
      },
      loadProjects() {
      request.get('/purchase/project/findAllLike')
        .then(response => {
          this.projects = response.data
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
.contract_list {
  /deep/.el-dialog__body{
    background:#f5f5f5;
    overflow-y: auto;
    max-height: 700px;
  }
  /deep/.el-form-item__content{
    height:auto;
    line-height:32px;
    margin-left:90px!important
  }
  .progress-tooltip-col {
    .progress-tooltip-col-div {
      text-align: center;
      min-height: 16px;
      .anticon {

      }
    }
  }
  /deep/.status-table {
    .selected {
      background: #e6f7ff;
    }
  }
}

</style>
